let socket;
let username;

function initWebChat() {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        username = rndNum(6);
        sessionStorage.removeItem("username");
        socket = new WebSocket("ws://" + window.location.hostname + ":" + wsPort + wsPath + "?fromId=" + username);
        sessionStorage.setItem("username", username);

        // socket.onopen = this.socketOpen;
        // // socket.onmessage = this.socketMessage;
        // socket.onclose = this.socketClose;
    } else {
        alert("您的浏览器不支持WebSocket协议！");
    }
    console.log("initChat")
}

const baseSize = 32;

function setRem() {
    const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    const htmlDom = document.getElementsByTagName('html')[0];
    //设置页面根节点字体大小
    htmlDom.style.fontSize = htmlWidth / 10 + 'px';
}

setRem();

window.onbeforeunload = function () {
    if (socket) {
        socket.onclose = function (evt) {
            console.log(evt);
        }
    }
};

//产生随机数函数
function rndNum(n) {
    // var rnd = "";
    // for (var i = 0; i < n; i++)
    //     rnd += Math.floor(Math.random() * 10);
    // return rnd;

    var len = n;//32长度
    var radix = 16;//16进制
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var ufromId = [], i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) ufromId[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        ufromId[8] = ufromId[13] = ufromId[18] = ufromId[23] = '-';
        ufromId[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!ufromId[i]) {
                r = 0 | Math.random() * 16;
                ufromId[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    console.log(ufromId);
    return ufromId.join('');
}